package com.liaoyifan.core.valid.validator;

import com.liaoyifan.core.valid.Message;
import com.liaoyifan.core.valid.constraints.DateRange;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.time.LocalDate;
import java.util.Map;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

@SuppressWarnings("unused")
public class DateRangeValidator implements ConstraintValidator<DateRange, Object> {

    private String message;
    private String start;
    private String end;

    @Override
    public void initialize(DateRange constraintAnnotation) {
        this.message = constraintAnnotation.message();
        this.start = constraintAnnotation.start();
        this.end = constraintAnnotation.end();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) return true;
        BeanWrapper beanWrapper = new BeanWrapperImpl(value);
        Object start = beanWrapper.getPropertyValue(this.start);
        Object end = beanWrapper.getPropertyValue(this.end);
        if (start == null || end == null) {
            return true;
        }
        LocalDate startDate = (LocalDate) start;
        LocalDate endDate = (LocalDate) end;
        if (startDate.isBefore(endDate)) {
            return true;
        }
        return Message.build(
                Message.get(this.message, Map.of("startDate", startDate, "endDate", endDate)),
                context);
    }
}
